import React from 'react';
import {
  StyleSheet,
  View,
  Text,
  Image,
  FlatList,
  TouchableOpacity,
  ScrollView,
  TextInput,
  TouchableWithoutFeedback
} from 'react-native';
var Dimensions = require('Dimensions');
var { width } = Dimensions.get('window');
import Loading from '../../../common/Loading'
import NavigatorBar from '../../../common/NavigationBar';
import {setSpText,setHW} from '../../../component/ScreenUtil'
import {listUserReply,insertReply} from '../../../api/my'
const { width,height } = Dimensions.get('window');
import { Toast } from 'teaset';
export default class ReplyDetail extends React.Component {
  constructor(props) {
    super(props);
    this.params = props.navigation.state.params;
    this.state = {
      loading:true,
      inputText:'',//评论内容
      dataList: []
    }
  }
  componentDidMount() {
    this._listUserReply()//评论列表
  }
  _listUserReply(){
    this.setState({loading:true})
      let json={
        ID:this.params.id,//评论id
        ROWS:10,
        PAGE:1
      }
      listUserReply(json).then(res=>{
          this.setState({loading:false,dataList:res.LIST})
         global.log(res,'评论回复----------------------')
      }).catch((res)=>{
        this.setState({loading:false})
      })
  }
  render() {
    return (
      <View style={styles.replyDetailBox}>
        <NavigatorBar
          title={'评论回复'}
          style={styles.navigatorBar}
          leftButton={this.renderLeftButton(require('../../../assets/imgs/back.png'))}
          rightButton={<Text style={styles.goKeShi} onPress={()=>this.goToKeShi()}>去往课时</Text>}
        />
        <ScrollView
          showsVerticalScrollIndicator={false}
        >
          <View style={[this.state.loading?{height:height - setHW(60)}:null]}>
            <View style={styles.listCon}>
                <FlatList
                  data={this.state.dataList}
                  showsVerticalScrollIndicator={true}
                  renderItem={({ item }) => this.renderItem(item)}
                  keyExtractor={(item) => item.ID}
                />
            </View>
          </View>
          {this.loadMore()}
          {this.loading()}
          {this.NoData()}
        </ScrollView>
        <View style={[styles.inputBox, styles.inputViewWrapper]}>
            <TextInput style={styles.input} 
                ref="textInput1"
                autoFocus={false}
                onChangeText={(text) => this.setState({ inputText: text })}
                value={this.state.inputText}
                underlineColorAndroid='transparent' 
                placeholder={'请输入评论'} />
            <Text style={[this.state.inputText?styles.sendBtnActive:styles.sendBtn]} onPress={()=>this.sendText()}>发布</Text>
        </View>
      </View>
    );
  }
 
  renderItem(item) {
    return (
      <TouchableWithoutFeedback>
        <View style={styles.item}>
          <View style={styles.itemLeft}>
            {this.headerIcon(item)}
          </View>
          <View style={styles.itemRight}>
            <Text style={styles.teacherText}>{this.MoreText(item.USERNAME,4)}</Text>
            <Text style={styles.replayContent}>{item.REPLYCONTENT}</Text>
            <View style={styles.timeBox}>
              <Image style={styles.timePic} source={require('../../../assets/imgs/timePic.png')} />
              <Text style={styles.time}>{item.CREATETIME}</Text>
            </View>
          </View>
        </View>
      </TouchableWithoutFeedback>
    )
  }
  // 正在加载or底部
	loadMore(){
		if(this.state.dataList.length>10){
			if(!this.state.loading){
				if(this.state.moreData){
					return(
						<View style={styles.loadMore}>
							<Text style={styles.loadMoreText}>正在加载中...</Text>
						</View>
					)
				}else{
					return(
						<View style={styles.loadMore}>
							<Text style={styles.loadMoreText}>已经全部加载完毕</Text>
						</View>
					)
				}
			}
		}
	}
  // 加载loading
	loading(){
		if(this.state.loading){
			return(
				<View style={{height:height - setHW(100)}}>
						<Loading/>
				</View>
			)
		}
	}
  // 没有数据
	NoData(){
		if(!this.state.loading&&!this.state.moreData&&!this.state.dataList.length){
			return(
				<Text style={styles.empty}>暂无数据</Text>
			)
		}
	}
  // 前往课时
  goToKeShi(){
    this.props.navigation.navigate('KeShiIndex', {
      id: this.state.dataList[0].COURSEPARTID
    });
  }
  // 点击发送回复评论时
  sendText(){
    let emp= this.state.inputText.split(" ").join("").length === 0//全是空格
    if(emp){
      Toast("请输入内容")
    }else{
        let json={
            "USER_ID": global.ECourseConstant.userInfo.uuid,//用户id
            "COMMENT_ID": this.params.id,//评论id
            "REPLY_CONTENT": this.state.inputText
        }
        insertReply(json).then(res=>{
            this.setState({ inputText: ''})//成功后清空
            this.refs.textInput1.blur()
            this._listUserReply()//重新刷新列表
        })
    }
  }
  // 字体超出
  MoreText(text,MaxNum){
    if(text){
        if(text.length>MaxNum){
            return(
                text.substring(0,MaxNum)+'...'
            )
        }else{
            return(
                text
            )
        }
    }
  }
  // 头像
  headerIcon(item){
    if(item.PIC&&item.PIC!=='null'){
        return(
            <Image style={styles.teacherIcon} source={{ uri: item.PIC }} />
        )
    }else{
        return(
            <Image style={styles.teacherIcon} source={require('../../../assets/imgs/default.png')}/>
        )
    }
  }
  // 渲染按钮 返回按钮
  renderLeftButton(image) {
    return <TouchableOpacity
      style={{ padding: 8 }}
      onPress={() => {
        if (this.props.navigation.state.routeName == "FirstRouter") {
          this.props.navigation.navigate("HomePage");
        } else {
          this.params&&this.params.refreshPage();//返回上一个页面的refreshPage()
          this.props.navigation.goBack();
        }
      }}>
      <Image style={{ width: 34, height: 34 }} source={image} />
    </TouchableOpacity>;
  }

}
const styles = StyleSheet.create({
  replyDetailBox: {
    flex:1,
    backgroundColor: '#fff',
  },
  goKeShi:{
    paddingRight:setHW(20),
    color:'#FF8A00',
  },
  listCon: {
    paddingTop: setHW(8),
    marginTop:setHW(10),
    backgroundColor:'#fff',
    marginBottom: setHW(150),
  },
  empty:{
    height:height - setHW(100),
    textAlign:'center',
    fontSize:setSpText(26),
    lineHeight:setHW(400),
  },
  // 回复
  inputViewWrapper: {
    width: '100%',
    position: 'absolute',
    width: width,
    bottom: 0,
  },
  inputBox: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      backgroundColor: '#fff',
      paddingTop: setHW(6),
      paddingRight:1,
      paddingBottom: setHW(6),
      width: width,
      height: setHW(90),
  },
  input: {
      height: setHW(72),
      backgroundColor: '#F5F5F5',
      textAlign: 'left',
      paddingLeft: setHW(12),
      paddingRight: setHW(6),
      width: width - setHW(130),
      paddingRight:setHW(6),
  },
  sendBtn:{
      height:setHW(76),
      width:setHW(120),
      fontSize:setSpText(28),
      paddingTop:setHW(20),
      color:'#ccc',
      borderWidth:1,
      borderColor:'#F5F5F5',
      justifyContent:'center',
      alignItems:'center',
      textAlign:'center'
  },
  sendBtnActive:{
      height:setHW(76),
      width:setHW(120),
      fontSize:setSpText(28),
      paddingTop:setHW(20),
      color:'#fff',
      backgroundColor:'#FF8A00',
      borderWidth:1,
      borderColor:'#FF8A00',
      justifyContent:'center',
      alignItems:'center',
      textAlign:'center',
      borderRadius:setHW(8),
  },
  item: {
    backgroundColor: '#fff',
    padding: setHW(20),
    flexDirection: 'row',
  },
  itemLeft: {
    width: setHW(94),
    marginRight: setHW(16),
  },
  itemRight: {
    width: width - setHW(150),
    borderBottomColor: '#EBEBEB',
    borderBottomWidth: 1,
  },
  teacherIcon: {
    height: setHW(94),
    width: setHW(94),
  },
  teacherText: {
    color: '#666666',
    fontSize:setSpText(28),
    marginBottom:setSpText(10),
  },
  replayContent:{
    fontSize:setSpText(30),
    lineHeight:setSpText(38),
  },
  timeBox: {
    height:setHW(72),
    flexDirection: 'row',
    alignItems:'center',
  },
  timePic: {
    height: setHW(32),
    width: setHW(32),
    marginRight: setHW(8),
  },
  time: {
    color: '#999999',
    fontSize:setSpText(26),
  },
})